package com.phpxiu.app.view.fragment;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.Permission;
import com.phpxiu.app.view.UIBase;
import com.phpxiu.app.view.dialog.Alert;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * @file
 * @brief Fragment的基本功能封装
 * @author 吴金洲
 * @note Fragment的基本功能封装
 *
 */
public class BaseFragment extends Fragment {
    protected final static String ARG="fragment_temp_arg";
    protected Activity act;
    protected Handler handler;
    protected View rootView;
    protected Alert mAlert;
    protected String arg;
    private List<String> deniedPermissions=new ArrayList<String>();//被拒绝权限列表

    public static BaseFragment newInstance(String arg){
        BaseFragment fragment=new BaseFragment();
        Bundle b = new Bundle();
        b.putString(ARG,arg);
        fragment.setArguments(b);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        act=getActivity();
        handler=new IHandler(this);
        arg=getArguments().getString(ARG);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return rootView;
    }

    public void handleMsg(Message msg){

    }

    /**
     * 界面显示时
     */
    public void onShow() {

    }

    /**
     * 语言切换事件
     */
    public void onSwitchLanguage() {

    }


    /**
     * 警告提示
     */
    protected void alert(String msg,View.OnClickListener clickListener){
        if(act==null||act.isFinishing()){
            return;
        }
        if(mAlert==null){
            mAlert=new Alert(act);
            mAlert.getWindow().getAttributes().width=(int) KKYApp.getInstance().screenWidth;
        }else {
            if(mAlert.isShowing()){
                mAlert.dismiss();
            }
        }
        mAlert.setOnClickListener(clickListener);
        mAlert.show();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(!isVisibleToUser) {
            if (mAlert != null && mAlert.isShowing()) {
                mAlert.dismiss();
            }
        }else{
            onShow();
        }
    }

    /**
     * 检测危险权限
     * @param code 请求代码
     */
    protected void requestMyPermissions(int code){
        switch (code){
            case Permission.REQUEST_COMMON:
                checkMyPermission(code,Permission.COMMON);
                break;
            case Permission.REQUEST_LOCATION:
                checkMyPermission(code,Permission.LOCATION);
                break;
            case Permission.REQUEST_PHOTO:
                checkMyPermission(code,Permission.PHOTO);
                break;
            case Permission.REQUEST_STORE:
                checkMyPermission(code,Permission.STORE);
                break;
        }
    }

    /**
     * 取到未授权的项
     * @param permissions
     */
    final private void checkMyPermission(int code,String[] permissions){
        deniedPermissions.clear();
        if(getContext()==null){
            return;
        }
        for (String p:permissions){
            int state= ActivityCompat.checkSelfPermission(getContext(), p);
            if(state!= PackageManager.PERMISSION_GRANTED){
                deniedPermissions.add(p);
            }
        }
        if(deniedPermissions.size()!=0){
            try {
                requestPermissions(deniedPermissions.toArray(new String[1]),code);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            onPermission(code);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean isPermission=true;
        if(grantResults.length>0){
            for (int state:grantResults){
                if(state!=PackageManager.PERMISSION_GRANTED){
                    isPermission=false;
                    break;
                }
            }
        }
        if(isPermission){
            onPermission(requestCode);
        }else{
            Toast.makeText(getContext(),getString(R.string.permission_title), Toast.LENGTH_LONG).show();
        }
    }

    /**
     *权限申请通过
     */
    protected void onPermission(int requestCode){

    }

    /**
     * 显示通知
     * @param title
     * @param msg
     */
    private void notification(int id,String title,String msg){
        if(getContext()==null){
            return;
        }
        NotificationManager mNotificationManager = (NotificationManager)getContext().getSystemService(getContext().NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(KKYApp.getInstance());
        mBuilder.setContentTitle(title)//设置通知栏标题
                .setContentText(msg)
                .setTicker(msg) //通知首次出现在通知栏，带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
                .setDefaults(Notification.DEFAULT_ALL)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合
                .setSmallIcon(R.mipmap.ic_launcher);//设置通知小ICON
        Notification notify = mBuilder.build();
        notify.flags |= Notification.FLAG_AUTO_CANCEL;
        mNotificationManager.notify(id,notify);
    }

    public void onInit(UIBase activity){

    }

    @Override
    public void onDestroyView() {
        if(handler!=null){
            handler.removeCallbacksAndMessages(null);
        }
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    static class IHandler extends Handler{
        private WeakReference<BaseFragment> fragment;

        IHandler(BaseFragment fragment) {
            this.fragment = new WeakReference<BaseFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            if(fragment!=null&&fragment.get()!=null) {
                fragment.get().handleMsg(msg);
            }
        }
    }
}
